package com.akk.module.hlbpay.service;

import com.akk.PayConstants;
import com.akk.common.enums.Enums;
import com.akk.module.avs.entity.AvsPayOrder;
import com.akk.module.avs.enums.AvsTransferStatus;
import com.akk.module.avs.service.AvsPayOrderService;
import com.akk.module.hlbpay.model.*;
import com.akk.module.hlbpay.util.Disguiser;
import com.akk.module.hlbpay.util.HlbBeanUtils;
import com.akk.module.hlbpay.util.HttpClientService;
import com.akk.module.hlbpay.util.RSA;
import com.akk.utils.AppendFile;
import com.akk.utils.IDUtils;
import com.akk.utils.RestResponse;
import com.alibaba.fastjson.JSONObject;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import org.apache.http.HttpStatus;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.akk.utils.RestResponse.AVS_ERROR_CODE;

@Service
public class HlbService {

    @Value("${temp.path}")
    private String path;

    @Autowired
    private AvsPayOrderService avsPayOrderService;

    private static final Logger log = LoggerFactory.getLogger(HlbService.class);

    //setp:1 创建订单
    public RestResponse createOrder(HlbCreateOrderRequest createOrder) {
        Map<String, String> map;
        try {
            createOrder.setP1_bizType(PayConstants.HLB_METHOD_QUICK_CREATE);
            createOrder.setP2_customerNumber(PayConstants.HLB_BUS_NUMBER);
            createOrder.setP7_idCardType("IDCARD");
            createOrder.setP5_timestamp(new SimpleDateFormat(
                    "yyyyMMddHHmmss").format(new Date()));
            createOrder.setP14_currency("CNY");
            createOrder.setP23_serverCallbackUrl(createOrder.getP23_serverCallbackUrl());
            map = HlbBeanUtils.convertBean(createOrder, new LinkedHashMap());
            String oriMessage = HlbBeanUtils.getSigned(map, null, PayConstants.HLB_SIGNKEY_SAME_PERSON);
            System.out.println(oriMessage);
            String sign = Disguiser.disguiseMD5(oriMessage.trim());
            System.out.println(sign);
            map.put("sign", sign);
            Map resultMap = HttpClientService.getHttpResp(map, PayConstants.HLB_REQUEST_URL_SAME_PERSON);

            if ((Integer) resultMap.get("statusCode") == HttpStatus.SC_OK) {
                String resultMsg = (String) resultMap.get("response");
                HlbCreateOrderResponse createOrderResponse = JSONObject.parseObject(resultMsg, HlbCreateOrderResponse.class);
                String[] excludes = {"rt3_retMsg"};
                String assemblyRespOriSign = HlbBeanUtils.getSigned(createOrderResponse, excludes, PayConstants.HLB_SIGNKEY_SAME_PERSON);
                String responseSign = createOrderResponse.getSign();
                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
                if (checkSign.equals(responseSign)) {
                    if ("0000".equals(createOrderResponse.getRt2_retCode())) {
                        Map<String, String> params = new HashMap<>();
                        params.put("orderNum", createOrderResponse.getRt5_orderId());
                        params.put("amount", createOrder.getP15_orderAmount());
                        params.put("cardNum", createOrder.getP9_cardNo().substring(0, 4) + "********" + createOrder.getP9_cardNo().substring(createOrder.getP9_cardNo().length() - 4));
                        return RestResponse.build(params);
                    } else if ("8004".equals(createOrderResponse.getRt2_retCode())) {
                        return RestResponse.build(AVS_ERROR_CODE, createOrderResponse.getRt3_retMsg());
                    } else {
                        return RestResponse.build("8004", createOrderResponse.getRt3_retMsg());
                    }
                }
                return RestResponse.build(AVS_ERROR_CODE, "支付失败，请确认后再次发起");
            }
            return RestResponse.build(AVS_ERROR_CODE, "服务器繁忙，请稍后再试");
        } catch (Exception e) {
            return RestResponse.build(AVS_ERROR_CODE, "提交的请求不被接受");
        }
    }

    //setp:2
    public RestResponse sendPayCode(HlbSendPayCodeRequest request) {
        request.setP1_bizType(PayConstants.HLB_METHOD_QUICK_SEND_CODE);
        request.setP2_customerNumber(PayConstants.HLB_BUS_NUMBER);
        request.setP4_timestamp(new SimpleDateFormat(
                "yyyyMMddHHmmss").format(new Date()));
        try {
            Map<String, String> map = HlbBeanUtils.convertBean(request, new LinkedHashMap());
            String oriMessage = HlbBeanUtils.getSigned(map, null, PayConstants.HLB_SIGNKEY_SAME_PERSON);
            String sign = Disguiser.disguiseMD5(oriMessage.trim());
            map.put("sign", sign);
            System.out.println("req:" + new Gson().toJson(map));
            Map<String, Object> resultMap = HttpClientService.getHttpResp(map, PayConstants.HLB_REQUEST_URL_SAME_PERSON);
            if ((Integer) (resultMap.get("statusCode")) == HttpStatus.SC_OK) {
                String resultMsg = (String) resultMap.get("response");
                HlbSendPayCodeResponse response = JSONObject.parseObject(resultMsg, HlbSendPayCodeResponse.class);
                String assemblyRespOriSign = HlbBeanUtils.getSigned(response, null, PayConstants.HLB_SIGNKEY_SAME_PERSON);
                String responseSign = response.getSign();
                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
                if (checkSign.equals(responseSign)) {
                    if ("0000".equals(response.getRt2_retCode())) {
                        return RestResponse.build(response);
                    } else {
                        return RestResponse.build(AVS_ERROR_CODE, response.getRt3_retMsg());
                    }
                }
                return RestResponse.build(AVS_ERROR_CODE, "支付失败，请确认后再次发起");

            }
            return RestResponse.build(AVS_ERROR_CODE, "服务器繁忙，请稍后再试");
        } catch (Exception e) {
            return RestResponse.build(AVS_ERROR_CODE, "提交的请求不被接受");
        }
    }

    public RestResponse confirmPay(HlbConfirmPayRequest request) {
        request.setP1_bizType(PayConstants.HLB_METHOD_QUICK_CONFIRM_PAY);
        request.setP2_customerNumber(PayConstants.HLB_BUS_NUMBER);
        request.setP4_timestamp(new SimpleDateFormat(
                "yyyyMMddHHmmss").format(new Date()));
        log.warn(">>>>>>>>>>>>>>>>>>>合利宝确认支付>>>>>>>>>>>>>>>>>");
        try {
            Map<String, String> map = HlbBeanUtils.convertBean(request, new LinkedHashMap());
            String oriMessage = HlbBeanUtils.getSigned(map, null, PayConstants.HLB_SIGNKEY_SAME_PERSON);
            String sign = Disguiser.disguiseMD5(oriMessage.trim());
//            String sign = RSA.sign(oriMessage,RSA.getPrivateKey(PayConstants.HLB_SIGNKEY_TRANSFER_RSA));
            map.put("sign", sign);
            log.warn("req:" + new Gson().toJson(map));
            Map<String, Object> resultMap = HttpClientService.getHttpResp(map, PayConstants.HLB_REQUEST_URL_SAME_PERSON);
            log.warn("res:" + new Gson().toJson(resultMap));
            if ((Integer) (resultMap.get("statusCode")) == HttpStatus.SC_OK) {
                String resultMsg = (String) resultMap.get("response");
                HlbConfirmPayResponse response = JSONObject.parseObject(resultMsg, HlbConfirmPayResponse.class);
                String assemblyRespOriSign = HlbBeanUtils.getSigned(response, null, PayConstants.HLB_SIGNKEY_SAME_PERSON);
                String responseSign = response.getSign();
                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
                if (checkSign.equals(responseSign)) {
                    if ("0000".equals(response.getRt2_retCode())) {
                        return RestResponse.build(response);
                    } else {
                        return RestResponse.build(AVS_ERROR_CODE, response.getRt3_retMsg());
                    }
                } else {
                    log.warn("签名验证失败");
                }
                return RestResponse.build(AVS_ERROR_CODE, "支付失败，请确认后再次发起");
            }
            return RestResponse.build(AVS_ERROR_CODE, "服务器繁忙，请稍后再试");
        } catch (Exception e) {
            log.error("error:" + e.getMessage() + ":" + e.getLocalizedMessage() + ":" + e.getCause());
            return RestResponse.build(AVS_ERROR_CODE, "提交的请求不被接受");
        }

    }

    public RestResponse bindCardPay(HlbBindCardPayRequest request) {
        request.setP1_bizType(PayConstants.HLB_QUICK_PAY_BIND_PAY);
        request.setP2_customerNumber(PayConstants.HLB_BUS_NUMBER);
        request.setP7_currency("CNY");
        request.setP6_timestamp(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
        log.warn(">>>>>>>>>>>>>>>>>合利宝绑卡支付>>>>>>>>>>>>>>>>>>>>>>>");
        try {
            Map<String, String> param = HlbBeanUtils.convertBean(request, new LinkedHashMap());
            String[] excludesReq = {"P17_validateCode"};
            String oriMessage = HlbBeanUtils.getSigned(request, excludesReq, PayConstants.HLB_SIGNKEY_SAME_PERSON);
            String sign = Disguiser.disguiseMD5(oriMessage.trim());
            param.put("sign", sign);
            log.warn("req:" + new Gson().toJson(param));
            Map<String, Object> resultMap = HttpClientService.getHttpResp(param, PayConstants.HLB_REQUEST_URL_SAME_PERSON);
            log.warn("res:" + new Gson().toJson(resultMap));
            if ((Integer) resultMap.get("statusCode") == HttpStatus.SC_OK) {
                String resultMsg = (String) resultMap.get("response");
                String[] excludes = {"rt3_retMsg"};
                HlbBindCardPayResponse response = JSONObject.parseObject(resultMsg, HlbBindCardPayResponse.class);
                String assemblyRespOriSign = HlbBeanUtils.getSigned(response, null, PayConstants.HLB_SIGNKEY_SAME_PERSON);
                String responseSign = response.getSign();
                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
                if (checkSign.equals(responseSign)) {
                    if ("0000".equals(response.getRt2_retCode())) {
                        return RestResponse.build(response);
                    } else {
                        return RestResponse.build(AVS_ERROR_CODE, response.getRt3_retMsg());
                    }
                }
                return RestResponse.build(AVS_ERROR_CODE, "支付失败，请确认后再次发起");
            }
            return RestResponse.build(AVS_ERROR_CODE, "服务器繁忙，请稍后再试");
        } catch (Exception e) {
            log.error("error:" + e.getMessage() + ":" + e.getLocalizedMessage() + ":" + e.getCause());
            return RestResponse.build(AVS_ERROR_CODE, "提交的请求不被接受");
        }
    }

    public RestResponse bindCardPaySms(HlbBindCardPaySmsRequest request) {
        request.setP1_bizType(PayConstants.HLB_QUICK_PAY_BIND_PAY_SEND_CODE);
        request.setP2_customerNumber(PayConstants.HLB_BUS_NUMBER);
        request.setP6_timestamp(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
        try {
            Map<String, String> param = HlbBeanUtils.convertBean(request, new LinkedHashMap());
            String oriMessage = HlbBeanUtils.getSigned(request, null, PayConstants.HLB_SIGNKEY_SAME_PERSON);
            String sign = Disguiser.disguiseMD5(oriMessage.trim());
            param.put("sign", sign);
            System.out.println("req:" + new Gson().toJson(param));
            Map<String, Object> resultMap = HttpClientService.getHttpResp(param, PayConstants.HLB_REQUEST_URL_SAME_PERSON);
            if ((Integer) resultMap.get("statusCode") == HttpStatus.SC_OK) {
                String resultMsg = (String) resultMap.get("response");
                String[] excludes = {"rt3_retMsg"};
                HlbBindCardPaySmsResponse response = JSONObject.parseObject(resultMsg, HlbBindCardPaySmsResponse.class);
                String assemblyRespOriSign = HlbBeanUtils.getSigned(response, excludes, PayConstants.HLB_SIGNKEY_SAME_PERSON);
                String responseSign = response.getSign();
                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
                if (checkSign.equals(responseSign)) {
                    if ("0000".equals(response.getRt2_retCode())) {
                        return RestResponse.build(response);
                    } else {
                        return RestResponse.build(AVS_ERROR_CODE, response.getRt3_retMsg());
                    }
                }
                return RestResponse.build(AVS_ERROR_CODE, "支付失败，请确认后再次发起");
            }
            return RestResponse.build(AVS_ERROR_CODE, "服务器繁忙，请稍后再试");
        } catch (Exception e) {
            return RestResponse.build(AVS_ERROR_CODE, "提交的请求不被接受");
        }

    }

    public RestResponse bindDepositCard(HlbBindBankCardRequest request, String type) {

        request.setP1_bizType(PayConstants.HLB_METHOD_BIND_CARD);
        request.setP2_customerNumber(PayConstants.HLB_BUS_NUMBER);
        request.setP6_idCardType("IDCARD");
        try {
            Map<String, String> map = HlbBeanUtils.convertBean(request, new LinkedHashMap());
            map.put("P11_operateType", type);
            String[] excludesRequest = {"P11_operateType"};
            String oriMessage = HlbBeanUtils.getSigned(map, excludesRequest, PayConstants.HLB_SIGNKEY_SAME_PERSON);
            String sign = Disguiser.disguiseMD5(oriMessage.trim());
            map.put("sign", sign);
            Map<String, Object> resultMap = HttpClientService.getHttpResp(map, PayConstants.HLB_REQUEST_URL_SAME_PERSON);
            if ((Integer) (resultMap.get("statusCode")) == org.apache.commons.httpclient.HttpStatus.SC_OK) {
                String resultMsg = (String) resultMap.get("response");
                HlbBindBankCardResponse response = JSONObject.parseObject(resultMsg, HlbBindBankCardResponse.class);
                String[] excludes = {"rt3_retMsg"};
                String assemblyRespOriSign = HlbBeanUtils.getSigned(response, excludes, PayConstants.HLB_SIGNKEY_SAME_PERSON);
                String responseSign = response.getSign();
                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
                if (checkSign.equals(responseSign)) {
                    if ("8035".equals(response.getRt2_retCode()))
                        return bindDepositCard(request, "UPDATE");
                    if ("0000".equals(response.getRt2_retCode())) {
                        return RestResponse.build(response);
                    } else {
                        return RestResponse.build(AVS_ERROR_CODE, response.getRt3_retMsg());
                    }
                }
                return RestResponse.build(AVS_ERROR_CODE, "支付失败，请确认后再次发起");
            }
            return RestResponse.build(AVS_ERROR_CODE, "服务器繁忙，请稍后再试");
        } catch (Exception e) {
            return RestResponse.build(AVS_ERROR_CODE, "提交的请求不被接受");
        }
    }

    public RestResponse deposit(HlbDepositRequest request) {
        request.setP1_bizType(PayConstants.HLB_METHOD_DEPOSIT);
        request.setP2_customerNumber(PayConstants.HLB_BUS_NUMBER);
        request.setP6_feeType("PAYER");
        log.warn("》》》》》》》》》》合利宝提现》》》》》》》》");
        try {
            Map<String, String> map = HlbBeanUtils.convertBean(request, new LinkedHashMap());
            String oriMessage = HlbBeanUtils.getSigned(request, null, PayConstants.HLB_SIGNKEY_SAME_PERSON);
            oriMessage = oriMessage.substring(0, oriMessage.lastIndexOf(PayConstants.HLB_SPLIT));
            String sign = RSA.sign(oriMessage, RSA.getPrivateKey(PayConstants.HLB_SIGNKEY_TRANSFER_RSA));
            map.put("sign", sign);
            log.warn("req:" + new Gson().toJson(map));
            Map<String, Object> resultMap = HttpClientService.getHttpResp(map, PayConstants.HLB_REQUEST_URL_TRANSFER);
            log.warn("res:" + new Gson().toJson(resultMap));
            if ((Integer) resultMap.get("statusCode") == org.apache.commons.httpclient.HttpStatus.SC_OK) {
                String resultMsg = (String) resultMap.get("response");
                HlbDepositResponse response = JSONObject.parseObject(resultMsg, HlbDepositResponse.class);
                String[] excludes = {"rt3_retMsg"};
                String assemblyRespOriSign = HlbBeanUtils.getSigned(response, excludes, PayConstants.HLB_SIGNKEY_SAME_PERSON);
                assemblyRespOriSign = assemblyRespOriSign.substring(0, assemblyRespOriSign.lastIndexOf(PayConstants.HLB_SPLIT) + 1);
                assemblyRespOriSign += PayConstants.HLB_SIGNKEY_TRANSFER_MD5;
                String responseSign = response.getSign();
                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
                if (checkSign.equals(responseSign)) {
                    if ("0000".equals(response.getRt2_retCode())) {
                        return RestResponse.build(response);
                    } else {
                        return RestResponse.build(AVS_ERROR_CODE, response.getRt3_retMsg());
                    }
                }
                return RestResponse.build(AVS_ERROR_CODE, "支付失败，请确认后再次发起");
            }
            return RestResponse.build(AVS_ERROR_CODE, "服务器繁忙，请稍后再试");
        } catch (Exception e) {
            log.error("error:" + e.getMessage() + ":" + e.getLocalizedMessage() + ":" + e.getCause());
            return RestResponse.build(AVS_ERROR_CODE, "提交的请求不被接受");
        }
    }

    // 查询账户余额
    public RestResponse queryMerchant() {
        HlbQueryMerChantRequest request = new HlbQueryMerChantRequest();
        request.setP1_bizType(PayConstants.HLB_QUERY_ACCOUNT);
        request.setP2_customerNumber(PayConstants.HLB_BUS_NUMBER);
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        request.setP3_timestamp(format.format(new Date()));
        try {
            Map<String, String> map = HlbBeanUtils.convertBean(request, new LinkedHashMap());
            String oriMessage = HlbBeanUtils.getSigned(map, null, PayConstants.HLB_MERCHANT_COMMON_MD5);
            String sign = Disguiser.disguiseMD5(oriMessage.trim());
            map.put("sign", sign);
            Map<String, Object> resultMap = HttpClientService.getHttpResp(map, PayConstants.HLB_QUERY_MERCHANT_URL);
            if ((Integer) (resultMap.get("statusCode")) == org.apache.commons.httpclient.HttpStatus.SC_OK) {
                String resultMsg = (String) resultMap.get("response");
                HlbQueryMerChantResponse response = JSONObject.parseObject(resultMsg, HlbQueryMerChantResponse.class);
//                String[] excludes = {"rt3_retMsg"};
                String assemblyRespOriSign = HlbBeanUtils.getSigned(response, null, PayConstants.HLB_MERCHANT_COMMON_MD5);
                String responseSign = response.getSign();
                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
                if (checkSign.equals(responseSign)) {
                    if ("0000".equals(response.getRt2_retCode())) {
                        return RestResponse.build(response);
                    } else {
                        return RestResponse.build(AVS_ERROR_CODE, response.getRt3_retMsg());
                    }
                }
                return RestResponse.build(AVS_ERROR_CODE, "签名验证失败");
            }
            return RestResponse.build(AVS_ERROR_CODE, "查询失败");
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.build(AVS_ERROR_CODE, "查询失败");
        }
    }

    public RestResponse transferQuery(String orderNum) {
        HlbTransferQueryRequest request = new HlbTransferQueryRequest();
        request.setP1_bizType(PayConstants.HLB_TRANSFER_QUERY_BIZTYPE);
        request.setP2_orderId(orderNum);
        request.setP3_customerNumber(PayConstants.HLB_BUS_NUMBER);
        try {
            Map<String, String> map = HlbBeanUtils.convertBean(request, new LinkedHashMap());
            String oriMessage = HlbBeanUtils.getSigned(request, null, PayConstants.HLB_SIGNKEY_SAME_PERSON);
            oriMessage = oriMessage.substring(0, oriMessage.lastIndexOf(PayConstants.HLB_SPLIT));
            String sign = RSA.sign(oriMessage, RSA.getPrivateKey(PayConstants.HLB_SIGNKEY_TRANSFER_RSA));
            map.put("sign", sign);
            Map<String, Object> resultMap = HttpClientService.getHttpResp(map, PayConstants.HLB_TRANSFER_QUERY_URL);
            if ((Integer) (resultMap.get("statusCode")) == org.apache.commons.httpclient.HttpStatus.SC_OK) {
                String resultMsg = (String) resultMap.get("response");
                System.out.println(resultMsg);
                HlbTransferQueryResponse response = JSONObject.parseObject(resultMsg, HlbTransferQueryResponse.class);
                String[] excludes = {"rt3_retMsg"};
                String assemblyRespOriSign = HlbBeanUtils.getSigned(response, excludes, PayConstants.HLB_SIGNKEY_SAME_PERSON);
                assemblyRespOriSign = assemblyRespOriSign.substring(0, assemblyRespOriSign.lastIndexOf(PayConstants.HLB_SPLIT) + 1);
                assemblyRespOriSign += PayConstants.HLB_SIGNKEY_TRANSFER_MD5;
                String responseSign = response.getSign();
                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
                if (responseSign.equals(checkSign)) {
                    if (response.getRt2_retCode().equals("0000")) {
                        return RestResponse.build(response);
                    } else
                        return RestResponse.build(AVS_ERROR_CODE, response.getRt3_retMsg(), response);
                } else
                    return RestResponse.build(AVS_ERROR_CODE, "支付环境异常");
            } else
                return RestResponse.build(AVS_ERROR_CODE, "查询失败");
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.build(AVS_ERROR_CODE, "查询异常");
        }
    }

    public RestResponse orderQuery(String orderNum) {
        HlbOrderQueryRequest request = new HlbOrderQueryRequest();
        request.setP1_bizType(PayConstants.HLB_QUICK_PAY_QUERY);
        request.setP3_customerNumber(PayConstants.HLB_BUS_NUMBER);
        request.setP2_orderId(orderNum);
        try {
            Map<String, String> map = HlbBeanUtils.convertBean(request, new LinkedHashMap());
            String oriMessage = HlbBeanUtils.getSigned(map, null, PayConstants.HLB_SIGNKEY_SAME_PERSON);
            String sign = Disguiser.disguiseMD5(oriMessage.trim());
            map.put("sign", sign);
            Map<String, Object> resultMap = HttpClientService.getHttpResp(map, PayConstants.HLB_QUICK_PAY_QUERY_URL);
            if ((Integer) (resultMap.get("statusCode")) == org.apache.commons.httpclient.HttpStatus.SC_OK) {
                String resultMsg = (String) resultMap.get("response");
                String[] excludes = {};
                HlbOrderQueryResponse response = JSONObject.parseObject(resultMsg, HlbOrderQueryResponse.class);
                String assemblyRespOriSign = HlbBeanUtils.getSigned(response, excludes, PayConstants.HLB_SIGNKEY_SAME_PERSON);
                String responseSign = response.getSign();
                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
                if (checkSign.equals(responseSign)) {
                    return RestResponse.build(response);
                }
                return RestResponse.build(AVS_ERROR_CODE, "签名验证失败");
            }
            return RestResponse.build(AVS_ERROR_CODE, "查询失败");
        } catch (Exception e) {
            return RestResponse.build(AVS_ERROR_CODE, "查询失败");
        }
    }

    public RestResponse depositProgress(AvsPayOrder order) {

        RestResponse restResponse = transferQuery(order.getOrderNum());
        int status = 0;
        if (Objects.equals(order.getStatus(), Enums.OrderStatusEnum.NO_PAYED.getValue())) {
            status = 0;
        } else if (restResponse.getCode().equals("20002")) {
            return restResponse;
        } else if (Objects.equals(order.getStatus(), Enums.OrderStatusEnum.SUCCESS_PAYED.getValue())) {
            status = 1;
        } else if (Objects.equals(order.getStatus(), Enums.OrderStatusEnum.SUCCESS_DEPOSIT.getValue())
                && restResponse.getCode().equals("1001")) {
            status = 4;
        } else if (restResponse.getCode().equals("1002")) {
            status = 2;
        } else if (restResponse.getCode().equals("1003")) {
            status = -3;
        } else if (restResponse.getCode().equals("2001")
                && (Objects.equals(order.getStatus(), Enums.OrderStatusEnum.SUCCESS_PAYED.getValue())
                || Objects.equals(order.getStatus(), Enums.OrderStatusEnum.SUCCESS_DEPOSIT.getValue()))) {
            status = -1;
        } else if (restResponse.getCode().equals("2002")
                && (Objects.equals(order.getStatus(), Enums.OrderStatusEnum.SUCCESS_PAYED.getValue())
                || Objects.equals(order.getStatus(), Enums.OrderStatusEnum.SUCCESS_DEPOSIT.getValue()))) {
            status = 1;
        }
        return RestResponse.build(status);
    }

    public RestResponse transferQueryHandler(AvsPayOrder order) {
        RestResponse restResponse = transferQuery(order.getOrderNum());
        if (order.getStatus() < Enums.OrderStatusEnum.SUCCESS_PAYED.getValue()) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "订单付款暂未成功");
        }
        if (restResponse != null && restResponse.getResult() != null) {
            HlbTransferQueryResponse response = (HlbTransferQueryResponse) restResponse.getResult();
            if (response.getRt2_retCode().equals("0000") && response.getRt7_orderStatus().equals(AvsTransferStatus.TransferStatus.SUCCESS.getValue())) {
                return RestResponse.build("1001", "此订单已经结算成功，如果长时间未到账，请联系客服处理。");
            } else if (response.getRt7_orderStatus().equals(AvsTransferStatus.TransferStatus.INIT.getValue())) {
                return RestResponse.build("1002", "通道已经接收此订单结算信息，如果长时间未到账，请联系客服处理。");
            } else if (response.getRt7_orderStatus().equals(AvsTransferStatus.TransferStatus.DOING.getValue())) {
                return RestResponse.build("1003", "通道正在此订单结算信息，如果长时间未到账，请联系客服处理。");
            } else if (response.getRt7_orderStatus().equals(AvsTransferStatus.TransferStatus.FAIL.getValue())
                    && (Objects.equals(order.getStatus(), Enums.OrderStatusEnum.SUCCESS_PAYED.getValue())
                    || Objects.equals(order.getStatus(), Enums.OrderStatusEnum.SUCCESS_DEPOSIT.getValue()))) {
                order.setStatus(Enums.OrderStatusEnum.SUCCESS_PAYED.getValue());
                avsPayOrderService.update(order);
                return RestResponse.build("2001", "此订单结算失败。失败原因：" + response.getRt3_retMsg());
            } else if (response.getRt7_orderStatus().equals("") && response.getRt2_retCode().equals("0005")
                    && (Objects.equals(order.getStatus(), Enums.OrderStatusEnum.SUCCESS_PAYED.getValue())
                    || Objects.equals(order.getStatus(), Enums.OrderStatusEnum.SUCCESS_DEPOSIT.getValue()))) {
                order.setStatus(Enums.OrderStatusEnum.SUCCESS_PAYED.getValue());
                avsPayOrderService.update(order);
                return RestResponse.build("2002", "此订单尚未提现");
            }
        }
        return RestResponse.build(RestResponse.AVS_ERROR_CODE, "查询失败");
    }

    // 查询用户绑卡信息
    public RestResponse queryUserBindCard(String payerId) {
        HlbQueryUserBindCardRequest request = new HlbQueryUserBindCardRequest();
        request.setP1_bizType("BankCardbindList");
        request.setP2_customerNumber(PayConstants.HLB_BUS_NUMBER);
        request.setP3_userId(payerId);
        request.setP5_timestamp(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
        try {
            Map<String, String> param = HlbBeanUtils.convertBean(request, new LinkedHashMap());
            String oriMessage = HlbBeanUtils.getSigned(request, null, PayConstants.HLB_SIGNKEY_SAME_PERSON);
            String sign = Disguiser.disguiseMD5(oriMessage.trim());
            param.put("sign", sign);
            Map<String, Object> resultMap = HttpClientService.getHttpResp(param, PayConstants.HLB_REQUEST_URL_SAME_PERSON);
            if ((Integer) resultMap.get("statusCode") == HttpStatus.SC_OK) {
                String resultMsg = (String) resultMap.get("response");
                String[] excludes = {"rt3_retMsg"};
//                resultMsg = resultMsg.replaceAll("\\\\","");
                Gson gson = new Gson();
                Map responseMap = gson.fromJson(resultMsg, LinkedHashMap.class);
                String jsonStr = responseMap.get("rt5_bindCardList").toString();
                responseMap.remove("rt5_bindCardList");
                resultMsg = gson.toJson(responseMap);
                List<HlbQueryCardInfo> list = gson.fromJson(jsonStr, new TypeToken<List<HlbQueryCardInfo>>() {
                }.getType());
                HlbQueryUserBindCardResponse response = gson.fromJson(resultMsg, HlbQueryUserBindCardResponse.class);
                response.setRt5_bindCardList(list);
                String assemblyRespOriSign = HlbBeanUtils.getSigned(response, excludes, PayConstants.HLB_SIGNKEY_SAME_PERSON);
                String responseSign = response.getSign();
                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
                if (checkSign.equals(responseSign)) {
                    if ("0000".equals(response.getRt2_retCode())) {
                        return RestResponse.build(response);
                    } else {
                        return RestResponse.build(AVS_ERROR_CODE, response.getRt3_retMsg());
                    }
                }
                return RestResponse.build(AVS_ERROR_CODE, "查询失败");
            }
            return RestResponse.build(AVS_ERROR_CODE, "服务器繁忙，请稍后再试");
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.build(AVS_ERROR_CODE, "提交的请求不被接受");
        }
    }

    // 解除绑定
    public RestResponse unBind(String payerId, String bindId) {
        HlbUnbindCardRequest request = new HlbUnbindCardRequest();
        request.setP1_bizType("BankCardUnbind");
        request.setP2_customerNumber(PayConstants.HLB_BUS_NUMBER);
        request.setP3_userId(payerId);
        request.setP4_bindId(bindId);
        request.setP5_orderId(IDUtils.getUniqueNum14());
        request.setP6_timestamp(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
        try {
            Map<String, String> map = HlbBeanUtils.convertBean(request, new LinkedHashMap());
            String oriMessage = HlbBeanUtils.getSigned(map, null, PayConstants.HLB_SIGNKEY_SAME_PERSON);
            String sign = Disguiser.disguiseMD5(oriMessage.trim());
            map.put("sign", sign);
            Map<String, Object> resultMap = HttpClientService.getHttpResp(map, PayConstants.HLB_QUICK_PAY_QUERY_URL);
            if ((Integer) (resultMap.get("statusCode")) == org.apache.commons.httpclient.HttpStatus.SC_OK) {
                String resultMsg = (String) resultMap.get("response");
                String[] excludes = {"rt3_retMsg"};
                HlbUnbindCardResponse response = JSONObject.parseObject(resultMsg, HlbUnbindCardResponse.class);
                String assemblyRespOriSign = HlbBeanUtils.getSigned(response, excludes, PayConstants.HLB_SIGNKEY_SAME_PERSON);
                String responseSign = response.getSign();
                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
                if (checkSign.equals(responseSign)) {
                    return RestResponse.build(response);
                }
                return RestResponse.build(AVS_ERROR_CODE, "签名验证失败");
            }
            return RestResponse.build(AVS_ERROR_CODE, "操作失败");
        } catch (Exception e) {
            return RestResponse.build(AVS_ERROR_CODE, "操作失败");
        }
    }

    @Test
    public void signTest() throws IllegalAccessException, IntrospectionException, InvocationTargetException {
        String json = "{\"P1_bizType\":\"QuickPayBindPay\",\"P2_customerNumber\":\"C1800001871\",\"P3_bindId\":\"8d8f4e33791d441881c1e0471e260daa\",\"P4_userId\":\"15119228772339644\",\"P5_orderId\":\"17121311503510146\",\"P6_timestamp\":\"20171213115303\",\"P7_currency\":\"CNY\",\"P8_orderAmount\":\"0.12\",\"P9_goodsName\":\"极速收款\",\"P10_goodsDesc\":\"极速收款\",\"P11_terminalType\":\"UUID\",\"P12_terminalId\":\"950de1d5-50a2-4523-9630-b3d59a93c060\",\"P13_orderIp\":\"118.112.91.73\",\"P14_period\":\"10\",\"P15_periodUnit\":\"Minute\",\"P17_validateCode\":\"444444\"}";

        HlbBindCardPayRequest request = new Gson().fromJson(json, HlbBindCardPayRequest.class);
        Map<String, String> param = HlbBeanUtils.convertBean(request, new LinkedHashMap());
        String[] excludesReq = {"P17_validateCode"};
        String oriMessage = HlbBeanUtils.getSigned(request, excludesReq, PayConstants.HLB_SIGNKEY_SAME_PERSON);
        String sign = Disguiser.disguiseMD5(oriMessage.trim());
        param.put("sign", sign);
        System.out.println("str:" + oriMessage);
        System.out.println("sgin:" + sign);
    }

    @Test
    public void test() {
        RestResponse restResponse = transferQuery("MP18591848728284");
        System.out.println(restResponse.getCode());
        System.out.println(new Gson().toJson(restResponse));
    }

    @Test
    public void orderTest() {
        RestResponse restResponse = orderQuery("CW4956657897409");
        System.out.println(restResponse.getCode());
        System.out.println(new Gson().toJson(restResponse));
    }

    @Test
    public void queryAmount() {
        RestResponse restResponse = queryMerchant();
        System.out.print(new Gson().toJson(restResponse));
    }

    @Test
    public void queryUserBindCard() {
        RestResponse restResponse = queryUserBindCard("bd15e805c2b94efcad75d661628522c9");
        System.out.println(new Gson().toJson(restResponse));
    }

    @Test
    public void unBind() {
        String json = "{\"P1_bizType\":\"SettlementCardBind\",\"P2_customerNumber\":\"C1800001871\",\"P3_userId\":\"M1802050146597\",\"P4_orderId\":\"18041211250532974\",\"P5_payerName\":\"陈敬\\n\",\"P6_idCardType\":\"IDCARD\",\"P7_idCardNo\":\"220622198202260029\",\"P8_cardNo\":\"6230521870001970378\",\"P9_phone\":\"\",\"P10_bankUnionCode\":\"\",\"P11_operateType\":\"ADD\",\"P12_isEncrypt\":\"\",\"P13_bindId\":\"\"}";
        HlbBindBankCardRequest request = new Gson().fromJson(json, HlbBindBankCardRequest.class);
        RestResponse restResponse = bindDepositCard(request, "ADD");
//        RestResponse restResponse = unBind("bd15e805c2b94efcad75d661628522c9","0439fdadfd1b4511bd6f2f3219756d7f");
//        System.out.println(Disguiser.disguiseMD5("&SettlementCardBind&C1800001871&2&18022311470493032&李正&IDCARD&511921199508216738&6231561600104912&&&KaQYmttleKPy9srrwapZ79Aev0cLf9Je"));
        System.out.println(new Gson().toJson(restResponse));
    }
}
